<template>
  <Svga v-if="param.loading" :width="100" :height="100"></Svga>
  <div v-else class="app-container">
    <div style="font-weight: 700;padding-bottom: 20px;">
      订单号：{{ rowData.orderNo }}
    </div>
    <Progress :userRole="'boxAgent'" :orderStatus="param.newStep" :payStatus="rowData.payStatus" />

    <div class="order-info">

      <el-row v-if="param.newStep < 30" style="margin-bottom: 10px">
        <el-button-group v-if="param.newStep >= 10">
          <el-button icon="edit" @click="showPackingList">查看提箱单</el-button>
          <!-- <el-button icon="edit" @click="download('tiXiang')">下载提箱单</el-button> -->
        </el-button-group>
        <el-button-group style="margin-left:20px; ">
          <el-button v-if="param.newStep >= 5 && rowData.status != 15 && rowData.invoiceStatus == 5" icon="edit"
            @click="param.drawer = true">
            <span>申请发票</span>
          </el-button>
          <el-button v-if="param.newStep >= 5 && rowData.invoiceStatus == 15" icon="edit"
            @click="param.drawerInvoiceInfo = true">
            <span>查看发票 </span>
          </el-button>
          <!-- <el-button icon="edit" v-if="param.newStep >= 20 && rowData.invoiceStatus == 15"
            @click="download('faPiao')">下载发票</el-button> -->
        </el-button-group>
        <el-button-group v-if="param.newStep >= 20 && rowData.returnBoxNo" style="margin-left:20px; ">
          <el-button icon="edit" @click="showReturnInfo">查看还箱单</el-button>
          <el-button icon="edit" @click="download('huanXiang')">下载还箱单</el-button>
        </el-button-group>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="18">
          <el-card style="box-sizing: border-box;padding: 10px;">
            <el-row :gutter="10">
              <el-col :span="12">
                <span style="font-size: 16px;font-weight: bold;">{{ rowData.companyName }}</span>
                <div m="t-4" style="margin-top: 10px;">
                  <el-carousel trigger="click">
                    <el-carousel-item v-for="item in rowData.mainFileList" :key="item" style="height: 100%;">
                      <img :src="item.url" style="height: 100%;width: 100%" />
                    </el-carousel-item>
                  </el-carousel>
                </div>
              </el-col>
              <el-col :span="12">
                <div style="font-size: 14px;text-align: left; box-sizing: border-box;padding: 10px 40px 10px 40px;">
                  <el-row :gutter="10">
                    <el-col :span="11">
                      <span style="font-weight: bolder;font-size: 18px;">{{ rowData.carryCityName }}</span>
                      <div style="margin-top: 10px;color: #aaa;">
                        提箱城市：{{ rowData.carryCityName }}/{{ rowData.carryCountryName }}
                      </div>
                    </el-col>
                    <el-col :span="2"><img style="text-align: center; width: 17px;" src="@/assets/icons/svg/right.svg">
                    </el-col>
                    <el-col :span="11" style="text-align: right;">
                      <span style="font-weight: 800;font-size: 18px;">{{ rowData.returnCityName }}</span>
                      <div style="margin-top: 10px;color: #aaa;">
                        还箱城市：{{ rowData.returnCityName }}/{{ rowData.returnCountryName }}
                      </div>
                    </el-col>
                  </el-row>
                  <!-- stamp -->
                  <stamp :rowData="rowData" :rentSource="5" />
                  <stampCancel :rowData="rowData" :pageType="'rentBox'" :canceledType="rowData.canceledType"
                    :roleType="'agent'" style="margin-right: 50px;" />
                  <!-- stampCancel -->
                  <el-row class="marginTop30" align="middle">  
                    <el-col :span="6">租赁单价</el-col>
                    <el-col :span="5">
                      <el-tooltip class="box-item" effect="dark" :content="currency + rowData.unitPrice" placement="top-start">
                        <span style="color: #eb2a2a;width: 100%;display: inline-block;" class="text-ellipsis">{{ currency }} {{rowData.unitPrice}}</span>
                      </el-tooltip>
                    </el-col>
               
                  </el-row>
                  <el-row class="marginTop30">
                    <el-col :span="6">箱使期</el-col>
                    <el-col :span="5" style="position: relative;">
                      <el-tooltip class="box-item" effect="dark" :content="rowData.boxUsagePeriod + '天'" placement="top-start">
                        <span style="width: 100%;display: inline-block;" class="text-ellipsis">{{rowData.boxUsagePeriod}}天</span> 
                      </el-tooltip> 
                    </el-col>
                  </el-row>
                  <el-row class="marginTop30">
                    <el-col :span="6">箱型</el-col>
                    <el-col :span="12">{{ boxTypeFilter(rowData.boxType) }}</el-col>
                  </el-row>
                  <el-row class="marginTop30">
                    <el-col :span="6">箱况</el-col>
                    <el-col :span="12">{{ boxConditionFilter(rowData.boxCondition) }}</el-col>
                  </el-row>
                  <el-row class="marginTop30">
                    <el-col :span="6">箱量</el-col>
                    <el-col :span="12">{{ rowData.boxQuantity }} &nbsp;个</el-col>
                  </el-row>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card style="height: 100%;position:relative" >
            <el-row class="marginTop20">
              <el-col :span="12">应付箱量</el-col>
              <el-col :span="12" class="text-right" >{{ rowData.containerQuantity || 0 }}</el-col>
            </el-row>
            <el-row class="marginTop10">
              <el-col :span="12">租箱金额</el-col>
              <el-col :span="12" class="text-right" style="color: #eb2a2a;">{{ currency }} {{ rowData.amount || 0 }}</el-col>
            </el-row>
            <el-row class="marginTop10"> 
              <el-col :span="12">优惠券</el-col>
              <el-col :span="12" class="text-right">{{ rowData.couponAmount || '0.00' }}</el-col>
            </el-row>
            <el-row style="border-top: #999999 1px dashed;position:absolute;bottom:20px;width: 88%;" class="marginTop10">
                <el-col :span="24">
                  <el-row class="marginTop10">
                    <el-col :span="12">合计</el-col>
                    <el-col :span="12" class="text-right" style="color: #eb2a2a;">{{ currency }} {{ rowData.conventAmount || 0 }}</el-col>
                  </el-row>
     
                  <!-- <el-row class="marginTop10">
                    <el-col :span="12">应付租箱费</el-col>
                    <el-col :span="12" class="text-right" style="color: #eb2a2a;">{{ currency }} {{ numMulti(rowData.containerQuantity,
                    rowData.unitPrice) }}</el-col>
                  </el-row> -->
                </el-col>
            </el-row>
          </el-card>
          <!-- <el-card style="height: 100%;box-sizing: border-box;padding: 10px;">
            <div style="font-weight: 700;font-size: 15px;margin:10px 0 10px 0;">
              <span style="width:3px;height:10px;background-color: #2158F3;font-size: 12px;"> &nbsp</span>&nbsp租赁费用
            </div>
            <table style="font-size: 14px;width: 400px;margin-top: 20px;width:100%">
              <tr style="width: 100px;">
                <td>订单金额</td>
                <td align="right"> {{ currency }} {{ rowData.amount || 0 }}</td>
              </tr>
              <tr style="width: 100px;">
                <td>应付箱量</td>
                <td align="right">{{ rowData.containerQuantity || 0 }}</td>
              </tr>
              <tr style="width: 100px;">
                <td>租箱</td>
                <td align="right">{{ boxTypeFilter(rowData.boxType) }}*{{ rowData.containerQuantity }}</td>
              </tr>
              <tr>
                <td>优惠券</td>
                <td style="color: red;" align="right">
                  <span style="margin-left:-12px">-</span> ￥ {{ rowData.couponAmount || '0.00' }}
                </td>
              </tr>
              <tr>
                <td>折合</td>
                <td align="right">$ {{ rowData.conventAmount }}</td>
              </tr>
              <tr>
                <td>本单执行汇率</td>
                <td align="right">1美元 = {{ rowData.rate }} 元</td>
              </tr>
              <tr style="height: 100px;">

              </tr>
              <tr>
                <template v-if="rowData.payStatus < 15">
                  <td>应付租箱费</td>
                  <td align="right" style="color: red;">{{ currency }} {{ numMulti(rowData.containerQuantity,
                    rowData.unitPrice) }}
                  </td>
                </template>
                <template v-else>
                  <td>实付租箱费</td>
                  <td align="right" style="color: red;">{{ currency }} {{ rowData.conventAmount }}</td>
                </template>
              </tr>
            </table>
            <div style="height: 1px;margin-top: -50px; border-bottom:2px Dotted  #999999; width: 100%;"></div>

          </el-card> -->
        </el-col>
      </el-row>
      <el-card class="pag-container">
        <span class="_before">订单信息</span>
        <el-form inline label-width="60px" style="margin-top: 10px;" label-position="left">
          <el-form-item>
            <div>预计提箱日期</div>
            <el-date-picker v-model="rowData.planPickupDate" disabled type="date" style="width:100%" />
          </el-form-item>
          <el-form-item>
            <div>支付方式</div>
            <el-select v-model="rowData.paymentMethod" disabled style="width:100%;min-width: 200px;" placeholder="选择">
              <el-option v-for="item in param.paymentMethodList" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div>联系人</div>
            <el-input v-model="rowData.contacts" disabled style="width:100%"></el-input>
          </el-form-item>
          <el-form-item>
            <div>联系电话</div>
            <el-input v-model="rowData.tel" disabled style="width:100%">
              <template #prepend v-if="rowData.agentUserAreaCode"> + {{ rowData.agentUserAreaCode }}</template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <div>结算账期</div>
            <el-input v-model="rowData.period" disabled style="width:100%">
              <template #append> 天</template>
            </el-input>
          </el-form-item>
          <el-form-item style="min-width:600px">
            <div>留言</div>
            <el-input v-model="rowData.leaveMsg" disabled style="width:100%"></el-input>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card class="pag-container">
        <span class="_before">订单分配</span>
        <div style="margin-top: 20px;width: 260px;font-size: 14px;">
          <div>经办人</div>
          <el-select v-model="param.handleUser" disabled placeholder="请选择">
            <el-option v-for="item in param.handleUserList" :key="item.handleUserId" :label="item.handleUserName"
              :value="item.handleUserId" />
          </el-select>
        </div>
        <!-- {{rowData.allocation}} -->
        <div v-for="(item, index) in rowData.allocation" :key="index">
          <el-form label-width="60px" inline style="margin-top: 10px;" label-position="left">
            <el-form-item style="width:260px">
              <div>业务员</div>
              <el-select v-model="item.businessUserName" disabled style="width:100%" placeholder="请选择">
                <el-option v-for="item in param.businessUserList" :key="item.businessUserId"
                  :label="item.businessUserName" :value="item.businessUserId" />
              </el-select>
            </el-form-item>
            <el-form-item style="width:260px">
              <div>操作员</div>
              <el-select v-model="item.operateUsers" disabled multiple placeholder="请选择" style="width:100%">
                <el-option v-for="(item2,index) in item.operateUser" :key="index" :label="item2.operateUserName"
                  :value="item2.operateUserId" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <div>业务编号</div>
              <el-input v-model="item.businessNo" disabled placeholder="请输入业务编号"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      <!-- 按钮/反馈信息展示 -->
      <el-card class="pag-container">
        <div v-if="rowData.rejectReason && rowData.currentNodeType == 5" style="text-align: center;">
          <span>拒绝原因：</span>{{ rowData.rejectReason }}
        </div>
        <div v-if="rowData.status == 40 && rowData.canceledType == 5" style="text-align: center;margin-bottom: 20px;">
          <span> 取消原因： </span>
          <span>{{ rowData.remark }} </span>
        </div>
        <div v-if="rowData.currentNodeType == 25" style="width: 80%;margin: 0 auto;">
          <div style="font-weight: 700;font-size: 15px; ">
            <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>审核信息
          </div>
          <h4>
            <redStar />驳回原因
          </h4>
          <el-input type="textarea" :rows="4" v-model="rowData.reviewRemark" placeholder="请输入驳回原因" />
        </div>
        <div style="width:100%;text-align: center;margin-top: 10px;">
          <template v-if="rowData.status == 40 && rowData.canceledType == 5">
            <el-button @click="handleShowWarning('rejectCancel')" type="danger" round> 拒 绝 </el-button>
            <el-button v-if="rowData.currentNodeType == 10" @click="handleMakeSure" type="primary" round> 同 意
            </el-button>
          </template>
          <el-button v-if="param.newStep <= 15 && rowData.status != 3" @click="handleShowWarning('cancelOrder')"
            round>取消订单</el-button>
          <el-button v-if="rowData.invoiceStatus == 15 && rowData.payStatus == 5" @click="handleGoPay" type="primary"
            round>立即支付</el-button>
          <template v-if="rowData.currentNodeType == 15">
            <el-button @click="handleShowWarning('rejectOrder')" type="danger" round> 拒 绝 </el-button>
            <el-button @click="handleMakeSure" type="primary" round> 确 认 </el-button>
          </template>
          <template v-if="rowData.currentNodeType == 25">
            <el-button @click="handleShowWarning('checkReject')" type="danger" round> 驳 回 </el-button>
            <el-button @click="handleMakeSure" type="primary" round> 通 过 </el-button>
          </template>
          <el-button v-if="rowData.currentNodeType == 30 && rowData.status == 3" @click="showContract" type="primary">签署</el-button>
          <el-button v-if="rowData.currentNodeType == 30 && rowData.status == 3" @click="completeSigning(rowData.id)" type="primary">完成签署</el-button>
        </div>
      </el-card>

      <div v-if="param.newStep == 20" style="padding: 20px;width: 100%;text-align: center ">
        <!-- <span>待还箱量 <span style="color: #2158F3;">1 </span>个 </span> -->
        <!-- <el-button @click="param.newStep = 6" type="primary" style="margin-left: 20px">立即还箱</el-button> -->
      </div>
    </div>

    <!-- E签宝 -->
    <el-dialog v-model="param.dialogEVisibleWarning" @close="handleCloseEQianBao" title="签署" style="width: auto;">
      <iframe v-if="param.dialogEVisibleWarning" :src="param.longContractUrl" width="100%" height="800px"
        frameborder="0"></iframe>
    </el-dialog>
    <!-- 申请发票 -->
    <el-drawer v-model="param.drawer" :with-header="false">
      <div style="font-weight: 700;font-size: 15px;margin-bottom: 10px;">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>
        <span v-if="rowData.invoiceStatus == 5">申请发票</span>
        <span v-else>查看发票</span>
      </div>
      <invoiceTemplate style="margin-top: 10px;"></invoiceTemplate>
      <table style="width: 400px;margin-top: 30px;">
      <tbody>
        <tr style="width: 100px;">
          <td>
            <div style="width: 100px;">发票状态</div>
          </td>
          <td>{{ { 5: '未申请', 10: '待开票', 15: '已开票' }[rowData.invoiceStatus] }}</td>
        </tr>
        <tr>
          <td>发票内容</td>
          <td>租箱明细</td>
        </tr>
        <tr>
          <td>发票抬头</td>
          <td>
            <div style="word-break: break-all;">{{ rowData.invoiceTitle }}</div>
          </td>
        </tr>
        <tr>
          <td>发票号码</td>
          <td>
            <div style="word-break: break-all;">{{ rowData.invoiceNo }}</div>
          </td>
        </tr>
        <tr>
          <td>联系集装箱公司</td>
          <td>{{ rowData.tel }}</td>
        </tr>
        <tr>
          <td>在线咨询</td>
          <td><a href="#" style="color: dodgerblue;">联系客服</a></td>
        </tr>
      </tbody>
      </table>
      <el-form v-if="rowData.invoiceStatus == 5" style="margin-top: 30px">
        <el-form-item>
          <div style="width:100px;">
            <redStar />发票类型
          </div>
          <el-radio-group v-model="rowData.invoiceType">
            <el-radio v-for="item in param.invoiceTypeList" :value="item.value" :key="item.value"
              :label="item.label"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <div>
            <redStar />企业名称
          </div>
          <el-input v-model="rowData.invoiceTitle" type="textarea" maxlength="200" show-word-limit rows="1"
            style="width: 100%;" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item>
          <div>
            <redStar />统一社会信用代码
          </div>
          <el-input v-model="rowData.invoiceTaxNum" type="textarea" maxlength="18" rows="1" style="width: 100%;"
            placeholder="请输入统一社会信用代码"></el-input>
        </el-form-item>
        <el-form-item v-if="rowData.invoiceStatus == 5">
          <el-button @click="handleApplyInvoice" type="primary"
            style="margin-top: 40px;text-align: right;">提交</el-button>
        </el-form-item>
      </el-form>
      <iframe
        v-if="rowData.invoiceStatus == 15 && param.invoiceUrl && param.invoiceUrl.length > 0 && param.invoiceUrl[0].url"
        style="width:100%;height: auto;min-height: 400px;" :src="param.invoiceUrl[0].url + '#toolbar=0'">
      </iframe>

    </el-drawer>
    <!-- 发票信息 -->
    <el-drawer v-model="param.drawerInvoiceInfo" :with-header="false">
      <invoiceInfo :rowData="rowData" :param="param"></invoiceInfo>
    </el-drawer>
    <!-- 提箱单信息 -->
    <tixiangdanInfo ref="tixiangdanInfoRef" @tixiangdanInfoClick="txClick"  @tixiangdanInfoListClick="txListClick"></tixiangdanInfo>
    <!-- 提箱记录/还箱记录 -->
    <el-drawer v-model="param.dialogVisiblePackingRecord" :with-header="false">
      <packingRecord :rowData="param.recordType == 'tiXiang' ? packing : returnInfo" :oprName="param.recordType">
      </packingRecord>
    </el-drawer>
    <!-- 还箱单信息 -->
    <huanxiangdanInfo ref="huanxiangdanInfoRef" @huanxiangdanInfoClick="hxClick"  @huanxiangdanInfoListClick="hxListClick"></huanxiangdanInfo>

    <!-- 支付租箱费 -->
    <el-dialog v-model="param.dialogVisible" style="width:500px;box-sizing:bolder;padding:40px ">
      <span style="font-weight: 700;font-size: 15px;">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>支付租箱费
      </span>
      <table style="font-size: 14px;width: 400px;margin-top: 30px;">
        <tr style="width: 100px;">
          <td>箱型</td>
          <td>{{ boxTypeFilter(rowData.boxType) }}</td>
        </tr>
        <tr>
          <td>应提箱量</td>
          <td>{{ rowData.totalQuantity || rowData.boxQuantity }}</td>
        </tr>
        <tr>
          <td>实提箱量</td>
          <td>{{ rowData.packedQuantity }}</td>
        </tr>
        <tr>
          <td>应付租箱费</td>
          <td>￥ {{ rowData.conventAmount }}</td>
        </tr>
        <tr>
          <td>实付租箱费</td>
          <td>￥ {{ rowData.actualPayAmount }}</td>
        </tr>
        <tr>
          <td>优惠券</td>
          <td>{{ rowData.couponAmount }}</td>
        </tr>
      </table>
      <el-form style="margin-top: 20px">
        <el-form-item>
          <div>
            <redStar />支付方式
          </div>
          <el-select v-model="rowData.paymentMethod" style="width:100%;min-width: 200px;" placeholder="选择">
            <el-option v-for="item in param.paymentMethodList" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <div>
            <redStar />电子回执单
          </div>
          <imgUpload ref="invoiceRef" :drag="false" style="width:100%"></imgUpload>
        </el-form-item>
        <el-form-item>
          <div>
            <redStar />支付时间
          </div>
          <el-date-picker v-model="rowData.payDate" :clearable="false" :editable="false" type="date"
            style="width:100%" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handlePay" style="margin-top: 40px;text-align: right;">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 提示 -->
    <el-dialog v-model="param.dialogVisibleWarning" title="提示" style="width: 400px;">
      <el-form>
        <el-form-item v-if="param.warningName == 'cancelOrder'">
          <h3>确定取消订单吗？</h3>
        </el-form-item>
        <el-form-item prop="remark">
          <div v-if="param.warningName == 'cancelOrder'" style="width: 100%;">取消原因：</div>
          <div v-else style="width: 100%;">驳回原因：</div>
          <el-input v-model="warningForm.remark" type="textarea" rows="3" max="200" show-word-limit placeholder="请输入"
            style="width: 300px;" />
        </el-form-item>
        <el-form-item v-if="param.warningName == 'cancelOrder'">
          <el-button @click="handleCancel" type="primary" style="float: right;width: 100px;"> 确定
          </el-button>
        </el-form-item>
        <el-form-item v-if="param.warningName == 'rejectOrder'">
          <el-button @click="handleReject('rejectOrder')" type="primary" style="float: right;width: 100px;"> 确定
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 查看提箱单列表 -->
    <el-dialog v-model="param.pkdialogTable" title="提箱单列表">
      <el-table :data="param.packingList" header-align="center" >
        <el-table-column property="packingNo" label="提箱单号" align="center">
          <template #default="scope">
            <el-button link type="primary" size="default" @click.prevent="showPacking(scope.row)" >{{scope.row.packingNo}}</el-button>
          </template>
        </el-table-column>
        <el-table-column property="yardName" label="堆场名称" width="120" align="center"/>
        <el-table-column property="boxCondition" label="箱况" width="60" align="center"><!--箱况:boxCondition 5-全新   10-次新  15-适货 20-混提-->
          <template #default="scope">
            <template v-if="scope.row.boxCondition == 5">全新</template>
            <template v-if="scope.row.boxCondition == 10">次新</template>
            <template v-if="scope.row.boxCondition == 15">适货</template>
            <template v-if="scope.row.boxCondition == 20">混提</template>
            <template v-else>--</template>
          </template>
        </el-table-column>
        <el-table-column property="residuePackingDays" label="剩余提箱天数" width="110" align="center">
          <template #default="scope">
            {{scope.row.residuePackingDays}}天
          </template>
        </el-table-column>
        <el-table-column property="packingValidityPeriodStart" label="提箱单有效期范围" align="center">
          <template #default="scope">
            {{ scope.row.packingValidityPeriodStart?.substring(0,10) }}~{{scope.row.packingValidityPeriodEnd?.substring(0,10)}}
          </template>
        </el-table-column>
        <el-table-column property="agentName" label="客户" show-overflow-tooltip align="center"/>
        <el-table-column property="packingStatus" label="状态" width="80" align="center">  <!--提箱单状态:  5-已发放 10-已下载 15-提箱中 20-已完成 25-作废 30-已过期-->
          <template #default="scope">
            <template v-if="scope.row.packingStatus == 5">已发放</template>
            <template v-if="scope.row.packingStatus == 10">已下载</template>
            <template v-if="scope.row.packingStatus == 15">提箱中</template>
            <template v-if="scope.row.packingStatus == 20">已完成</template>
            <template v-if="scope.row.packingStatus == 25">作废</template>
            <template v-if="scope.row.packingStatus == 30">已过期</template>
            <template>--</template>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import invoiceInfo from '@/views/components/order/invoiceInfo.vue'
import { numAdd, numSub, numMulti } from '@/utils/compute'
import invoiceTemplate from '@/views/components/invoiceTemplate.vue'
import { downloadIamge } from '@/utils/download'
import Svga from '@/views/components/Svga'
import { formatDate } from '@/utils'
import Progress from '@/components/progress/index.vue'
import redStar from '@/views/components/redStar.vue';
import imgUpload from '@/components/upload/index.vue'
import { computed, onActivated, reactive, ref, getCurrentInstance } from 'vue';
import orderInfo from '@/store/modules/order'
import { getOrderInfo, cancelOrder } from '@/api/orderManage'
import { addRentRequestInvoice } from '@/api/invoice'
import { getPackingData,rentBoxList } from '@/api/orderManage/packing'
import { getReturnData} from '@/api/orderManage/returnBox'
import packingRecord from '@/views/components/tiXiangManage/packingRecord.vue'
import { payBoxLabelInvoice } from '@/api/invoice'
import yardInfoCard from '@/views/components/boxYard/yardInfo.vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { processApproved, processRejected } from '@/api/orderCheck/index'
import stamp from '@/views/components/stamp';
import { getContractList } from '@/api/contract/eQianBao'
import stampCancel from '@/views/components/stamp/stampCancel';
import tixiangdanInfo from '@/views/components/order/tixiangdanInfo.vue';
import huanxiangdanInfo from '@/views/components/order/huanxiangdanInfo.vue';

const param = reactive({
  loading: false,
  num: 1,
  activeNames: '',
  drawer: false,
  drawer1: false,
  drawer2: false,
  newStep: 1,
  dialogVisible: false,
  invoiceType: 5,
  invoiceTypeList: [
    { value: 5, label: '增值税普通发票' },
    { value: 10, label: '增值税专用发票' },
    // { value: 15, label: '形式发票' },
    // { value: 20, label: '其它' }
  ], //15-形式发票 20-其它

  //订单分配  
  handleUserList: [{ "handleUserId": 4, "handleUserName": "李四" }],
  paymentMethodList: [{ value: 5, label: '对公转账' }, { value: 10, label: '在线支付' }],
  operateUserList: [{ "operateUserId": 3, "operateUserName": "张三" }, { "operateUserId": 5, "operateUserName": "王五" }],
  businessUserList: [{ "businessUserId": 4, "businessUserName": "李四" }, { "businessUserId": 6, "businessUserName": "赵六" }],
  allocation: [{ 'operateUsers': [3, 5], "businessUser": 4, "businessNo": "NO1234567890" }],
  containerNoArry: [],
  invoiceUrl: [],
  pkdialogTable:false,//提箱单列表弹窗
  packingList:[] // 提箱单列表数据

})

const currency = computed(() => {
  return rowData.value.currency == 'CNY' ? '￥' : '$'
})

onActivated(() => {
  const rowData = orderInfo().rowData
  getSetOrderInfo(rowData)
 
})

//获取数据
const rowData = ref({})
const getSetOrderInfo = async (row: any) => {
  param.newStep = row.status
  // mainImgList.value = JSON.parse(row.allocation) // 订单主图从列表list数据获取
  if (!row.id) return
  param.loading = true
  await getOrderInfo(row.id).then((res: any) => {
    const result = res.data
    rowData.value = result
    param.newStep = result.status
    rowData.value.allocation = JSON.parse(result.allocation)
    param.handleUser = rowData.value.allocation[0]?.handleUserName
    rowData.value.allocation.forEach((el: any) => {
      el.operateUsers = operateUserFilter(el.operateUser)
    })
    rowData.value.mainFileList = JSON.parse(rowData.value.mainFileList)
    param.invoiceUrl = JSON.parse(rowData.value.invoiceUrl)
    param.loading = false
  })
}

const handleShowRecord = (val: string) => {
  param.dialogVisiblePackingRecord = true
  param.recordType = val
}

// const operaStrArr = ref([])
// const operateUsersCheck = (item)=>{
//   let operaStr = []
//   item.forEach((val) => {
//     operaStr.push(val.operateUserName)
//   })
//   operaStrArr.value = operaStr
// }

//show 提示窗口
const warningForm = ref({})
const handleShowWarning = (val: String) => {
  if (val == 'cancelOrder' || val == 'rejectOrder' || val == 'rejectCancel') { //取消订单、拒绝
    param.dialogVisibleWarning = true
    param.warningName = val
  }
  if (val == 'checkReject') { //审核驳回
    handleReject('checkReject')
  }
}
//取消订单
const handleCancel = () => {
  if (!warningForm.value.remark) {
    return ElMessage({ message: '请输入取消原因', type: 'warning' })
  }
  const data = {
    id: rowData.value.id,
    remark: warningForm.value.remark
  }
  cancelOrder(data).then(res => {
    param.newStep = 35
    param.dialogVisibleWarning = false
    getSetOrderInfo(rowData.value)
  })
}
//待确认->确认btn
const handleMakeSure = () => {
  if (!rowData.value || !rowData.value.processId) return ElMessage({ message: 'processId 未找到！', type: 'error' })
  const data = { "processId": rowData.value.processId }
  param.loading = true
  processApproved(data).then(() => {
    ElMessage({ message: '确认成功', type: 'success' })
    getSetOrderInfo(rowData.value)
    param.loading = false
  }).catch(() => {
    param.loading = false
  })
}
//待确认->拒绝btn、审核->驳回
const handleReject = (val: String) => {
  if (val == 'rejectOrder') { //拒绝
    if (!warningForm.value || !warningForm.value.remark) {
      return ElMessage({ message: '请输入拒绝 原因', type: 'warning' })
    }
    if (!rowData.value || !rowData.value.processId) return ElMessage({ message: 'processId 未找到！', type: 'error' })
    const data = { "processId": rowData.value.processId, "reviewRemark": warningForm.value.remark }
    processRejected(data).then(() => {
      ElMessage({ message: '驳回成功', type: 'success' })
      param.dialogVisibleWarning = false
      getSetOrderInfo(rowData.value)
      // orderInfo().setOrderInfo(rowData.value)
    })
  }
  if (val == 'checkReject') { //驳回
    if (!rowData.value || !rowData.value.reviewRemark) {
      return ElMessage({ message: '请输入驳回 原因', type: 'warning' })
    }
    if (!rowData.value || !rowData.value.processId) return ElMessage({ message: 'processId 未找到！', type: 'error' })
    const data = { "processId": rowData.value.processId, "reviewRemark": rowData.value.reviewRemark }
    processRejected(data).then(() => {
      ElMessage({ message: '驳回成功', type: 'success' })
      getSetOrderInfo(rowData.value)
    })
  }
}

//支付
const invoiceRef = ref()
const handleGoPay = () => {
  rowData.value.payDate = new Date()
  param.dialogVisible = true
}
const handlePay = () => {
  const imgList = invoiceRef.value.resultList || []
  if (imgList.length == 0) {
    return ElMessage({ message: '请上传电子回执单', type: 'warning' })
  }
  const data = {
    "id": rowData.value.invoiceId,
    "paymentMethod": rowData.value.paymentMethod,
    "payDate": rowData.value.payDate,
    "payUrl": JSON.stringify(imgList)
    // "payUrl": "[{\"name\":\"20240612/cddd81a833c64a7eab1da5c0aef8dfaf.docx\",\"returnReceiptFileName\":\"国际贸易供应链数字平台电子回执单.docx\",\"url\":\"http://47.122.3.254:9000/default/20240612/cddd81a833c64a7eab1da5c0aef8dfaf.docx\"}]"
  }
  payBoxLabelInvoice(data).then(res => {
    // param.newStep = 25
    param.dialogVisible = false
    getSetOrderInfo(rowData.value)
  })
}

//过滤
const boxTypeFilter = (val: any) => {
  let result = ''
  const boxConditionList = [{ value: 5, label: '40HQ' }, { value: 10, label: '40GP' }, { value: 15, label: '20HQ' }, { value: 20, label: '20GP' }]
  boxConditionList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const boxConditionFilter = (val: any) => {
  let result = ''
  const boxTypeList = [{ value: 15, label: '适货' }, { value: 10, label: '次新' }, { value: 20, label: '混提' },{ value: 5, label: '全新' }]
  boxTypeList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const operateUserFilter = (operateUsers: any) => {
  let result: any = []
  operateUsers.forEach((el: any) => {
    result.push(el.operateUserId)
  })
  return result
}
const statusFilter = (val: any) => {
  // let status: any = { 5: '已下单', 10: '待提未付', 15: '已提未付', 20: '待还未付', 25: '待还已付', 30: '已完成', 35: '已取消' }
  let status = { 5: '已发放', 10: '已下载', 15: '提箱中', 20: '已完成' }
  return status[val]
}
// 5 - 已下单 | 待开提箱单 10 - 待提未付 | 待提未收 15 - 已提未付 | 已提未收 20 - 待还未付 | 待还未收 25 - 待还已付 | 待还已收 30 - 已完成 35 - 已取消

//申请发票
const handleApplyInvoice = () => {
  if (!rowData.value.invoiceType) {
    return ElMessage({ message: '请选择发票类型', type: 'warning' })
  }
  if (!rowData.value.invoiceTitle) {
    return ElMessage({ message: '请输入企业名称', type: 'warning' })
  }
  // const regex = /^[0-9a-zA-Z\u4e00-\u9fa5]*$/; // 匹配数字、英文和汉字
  const regex = /^[a-zA-Z\u4e00-\u9fa5]*$/; // 匹配英文和汉字
  if (!regex.test(rowData.value.invoiceTitle)) {
    return ElMessage({ message: '企业名称只允许输入英文和汉字', type: 'warning' })
  }
  if (!rowData.value.invoiceTaxNum) {
    return ElMessage({ message: '请输入统一社会信用代码', type: 'warning' })
  }
  const invoiceTaxNumRegex = /^[0-9a-zA-Z]*$/; // 匹配数字、英文
  if (!invoiceTaxNumRegex.test(rowData.value.invoiceTaxNum)) {
    return ElMessage({ message: '社会信用代码只允许输入数字、英文', type: 'warning' })
  }
  const data = {
    "invoiceOrder": JSON.stringify([{ orderId: rowData.value.id, orderNo: rowData.value.orderNo }]),
    "invoiceTitle": rowData.value.invoiceTitle?.trim(),
    "invoiceType": rowData.value.invoiceType,
    "invoiceContent": "租箱明细",
    "creditCode": rowData.value.invoiceTaxNum?.trim(),
    "payCurrency": "CNY"
  }
  addRentRequestInvoice(data).then((res: any) => {
    getSetOrderInfo(rowData.value)
    param.drawer = false
  })
}

//提箱单详情



const packing = ref({})
const showPackingList = () => {
  rentBoxList(rowData.value.id).then((res: any) => {
    param.pkdialogTable = true
    param.packingList = res.data

  }).catch((err: any) => {
    ElMessage.warning("提箱单列表查询失败，请稍后再试")
  })
}
//提箱单信息
const tixiangdanInfoRef=ref()
const showPacking = async (val) => {
  param.pkdialogTable = false
  if (!val.packingId) {
    return ElMessage({ message: '暂无提箱单id信息', type: 'error' })
  }
  tixiangdanInfoRef.value.openBox(val.packingId)
}
//提箱单信息关闭回调
const txClick=(val)=>{
  packing.value=val
}
//提箱单信息列表回调
const txListClick=(val)=>{
  packing.value = val
  param.dialogVisiblePackingRecord = true
  param.recordType = 'tiXiang'
}

//查看还箱单详情
const returnInfo = ref({})
const huanxiangdanInfoRef=ref()

//还箱单详情
const showReturnInfo = () => {
  huanxiangdanInfoRef.value.openBox(rowData.value.returnBoxId)
}
//还箱单信息关闭回调
const hxClick=(val)=>{
  returnInfo.value=val
}
//还箱单信息列表回调
const hxListClick=(val)=>{
  returnInfo.value=val
  param.dialogVisiblePackingRecord = true
  param.recordType = 'huanXiang'
}


//下载
//packing 
const download = async (val: any) => {
  let fileUrl = null
  switch (val) {
    case 'tiXiang':
      await getPackingData(rowData.value.packingId).then((res: any) => {
        let pdfFile1 = JSON.parse(res.data.pdfFile)
        fileUrl = pdfFile1.url
      })
      break
    case 'faPiao':
      const urlList = JSON.parse(rowData.value.invoiceUrl)
      fileUrl = urlList[0].url
      break
    case 'huanXiang':
      await getReturnData(rowData.value.returnBoxId).then((res: any) => {
        const pdfFile = JSON.parse(res.data.pdfFile)
        fileUrl = pdfFile.url
      })
      break
  }

  if (!fileUrl) {
    ElMessage.error('chengzhi 未找到下载文件')
    return
  }
  downloadIamge(fileUrl)
}

// 调取 eQuanBao 长链接
const showContract = async (val: any) => {
  param.loading = true
  getContractList({ "orderId": rowData.value.id ,signflowStatus: 10, rescissionStatus: 5 }).then((res: any) => {
    param.longContractUrl = res.data[0].longContractUrl
    if (param.longContractUrl) {
      param.dialogEVisibleWarning = true
    } else {
      return ElMessage.warning('系统繁忙！请稍后再试')
    }
    param.loading = false
  }).catch(() => {
    ElMessage.warning('系统繁忙！请稍后再试')
    param.loading = false
  })
}

// 关闭弹窗
const handleCloseEQianBao = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '数据更新中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  await setTimeout(async () => {
    getSetOrderInfo(rowData.value)
    loading.close()
  }, 10000)
}

const { proxy } = getCurrentInstance()
const completeSigning = (id) => { 
  let reqParam = { // 5:租箱 10：回调（进口） 15：购箱 
    orderId:id,
    businessType:5
  }
  proxy.$common(reqParam).then((res) => { 
    if(res.code === "00000"){
      ElMessage.success('操作成功')
    }else{
      ElMessage.warning(res.msg)
    }
  })
}
</script>

<style lang="scss" scoped>
.order-info {
  margin-top: 10px;
}

.pag-container {
  margin-top: 10px;
  box-sizing: border-box;
  padding: 10px;
}

table>tr>td~td {
  font-weight: bold;
}
</style>